from django.db import models
from Apps.Profile.models import User
from django.utils import timezone


class Category(models.Model):
    """
    文章分类
    """
    name = models.CharField(max_length=100)

    class Meta:
        verbose_name = '分类'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Tag(models.Model):
    """
    标签
    """
    name = models.CharField(max_length=100)

    class Meta:
        verbose_name = '标签'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name


class Article(models.Model):
    """
    文章
    """
    title = models.CharField('标题', max_length=70)
    body = models.TextField('正文')
    created_time = models.DateTimeField('创建时间', default=timezone.now)
    modified_time = models.DateTimeField('修改时间')
    excerpt = models.CharField('摘要', max_length=200, blank=True)
    category = models.ForeignKey('Category', verbose_name='分类', on_delete=models.DO_NOTHING)
    tag = models.ManyToManyField('Tag', verbose_name='标签', blank=True)
    author = models.ForeignKey('Profile.User', verbose_name='作者', on_delete=models.DO_NOTHING)

    def save(self, *args, **kwargs):
        self.modified_time = timezone.now()

        super().save(*args, **kwargs)

    class Meta:
        verbose_name = '文章'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title


class Comment(models.Model):
    """
    评论
    """
    name = models.CharField('名字', max_length=50)
    text = models.TextField('内容')
    created_time = models.DateTimeField('创建时间', default=timezone.now)
    article = models.ForeignKey('Article', verbose_name='文章', on_delete=models.CASCADE)
    commenter = models.ForeignKey('Profile.User', verbose_name='评论者', on_delete=models.CASCADE)

    class Meta:
        verbose_name = '评论'
        verbose_name_plural = verbose_name

    def __str__(self):
        return '{}: {}'.format(self.name, self.text[:20])
